package tksDB

import (
	"fmt"
	"github.com/astaxie/goredis"
	. "github.com/bitly/go-simplejson"
	_ "github.com/go-sql-driver/mysql"
	"reflect"
	"strconv"
	"strings"
)

import (
	"tksUint"
)

type TksCache struct {
	ServerId int
	Redis    goredis.Client
}

func GetTypeName(obj interface{}) (typestr string) {
	typ := reflect.TypeOf(obj)
	typestr = typ.String()

	lastDotIndex := strings.LastIndex(typestr, ".")
	if lastDotIndex != -1 {
		typestr = typestr[lastDotIndex+1:]
	}

	return
}

func JsonToStruct(js *Json, u interface{}) {
	dataStruct := reflect.Indirect(reflect.ValueOf(u))
	dataStructType := dataStruct.Type()
	for i := 0; i < dataStructType.NumField(); i++ {
		field := dataStructType.Field(i)
		fieldv := dataStruct.Field(i)
		if field.Type.Kind() == reflect.Int {
			n, _ := js.Get(field.Name).Int()
			fieldv.SetInt(int64(n))
		} else if field.Type.Kind() == reflect.Int64 {
			n, _ := js.Get(field.Name).Int64()
			fieldv.SetInt(n)
		} else if field.Type.Kind() == reflect.String {
			s, _ := js.Get(field.Name).String()
			fieldv.SetString(s)
		} else if field.Type.Kind() == reflect.Bool {
			b, _ := js.Get(field.Name).Bool()
			fieldv.SetBool(b)
		}
	}
}

func InitRedis(host string, serverId int) *TksCache {
	c := new(TksCache)
	c.Redis.Addr = host
	c.ServerId = serverId
	return c
}

func (c *TksCache) SetDataIntoRedis(key string, u interface{}) error {
	data1, _ := tksUint.MsgToBuf(u)
	fmt.Printf("key: %s find from mysql, save set: %s,data: %s\n", key, GetTypeName(u), string(data1))
	c.Redis.Hset(GetTypeName(u)+strconv.Itoa(c.ServerId), key, data1)
	return nil
}

func (c *TksCache) GetDataFromRedis(key string, u interface{}) error {
	data, err := c.Redis.Hget(GetTypeName(u)+strconv.Itoa(c.ServerId), key)
	if err != nil {
		return err
	}
	fmt.Printf("find from Redis, save set: %s, data: %s\n", GetTypeName(u), string(data))
	j, err1 := tksUint.BufToMsg(data)
	if err1 != nil {
		return err1
	}
	JsonToStruct(j, u)
	return nil
}

func (c *TksCache) DelDataFromRedis(key string, u interface{}) error {
	c.Redis.Hdel(GetTypeName(u)+strconv.Itoa(c.ServerId), key)
	return nil
}
